package com.iworkh.spring.data.jdbc.tx.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.Map;

/**
 * StudentDao
 *
 * @author: iworkh-沐雨云楼
 * @date: 2019-12-20
 */
@Repository
public class StudentDao {
    @Autowired
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    public int getMoney(String id){
        Map<String, Object> paraMap = new HashMap<>();
        paraMap.put("id", id);

        String sqlCount = "select money from student where id=:id";

        return namedParameterJdbcTemplate.queryForObject(sqlCount, paraMap, Integer.class);

    }

    public void consume(String id, double price) throws RuntimeException {

        if (this.getMoney(id) < price) {
            throw new RuntimeException("金额不足");
        }

        String sql = "update student set money=money-:price where id=:id";

        Map<String, Object> paraMap = new HashMap<>();
        paraMap.put("id", id);
        paraMap.put("price", price);
        namedParameterJdbcTemplate.update(sql, paraMap);
    }
}
